<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="表单编码" prop="formCode">
        <el-input v-model="queryParams.formCode" placeholder="请输入表单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="表单名称" prop="formName">
        <el-input v-model="queryParams.formName" placeholder="请输入表单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="表单版本" prop="version">
        <el-input v-model="queryParams.version" placeholder="请输入表单版本" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['form:definition:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="definitionList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="50" align="center" key="id" prop="id">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="表单编码" align="center" prop="formCode" sortable="custom" :show-overflow-tooltip="true" />
      <el-table-column label="表单名称" align="center" prop="formName" sortable="custom" :show-overflow-tooltip="true" />
      <el-table-column label="表单版本" align="center" prop="version" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tag>{{scope.row.version}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否发布" align="center" prop="isPublish" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="dict.type.is_publish" :value="scope.row.isPublish" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom"
        :sort-orders="['descending', 'ascending']" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="230" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.formType === 0" size="mini" type="text" @click="handleDesign(scope.row)"
            v-hasPermi="['form:design:queryDesign']">表单设计</el-button>
          <el-button size="mini" type="text" v-if="scope.row.isPublish === 0" @click="handlePublish(scope.row.id)"
            v-hasPermi="['form:definition:publish']">发布</el-button>
          <el-button size="mini" type="text" v-if="scope.row.isPublish === 1" @click="handleUpPublish(scope.row.id)"
            v-hasPermi="['form:definition:upPublish']">取消发布</el-button>
          <el-button size="mini" type="text" @click="handleCopyDef(scope.row.id)"
            v-hasPermi="['form:definition:upPublish']">复制表单</el-button>
          <el-button size="mini" type="text" v-if="scope.row.isPublish === 0" @click="handleUpdate(scope.row.id)"
            v-hasPermi="['form:definition:edit']">修改</el-button>
          <el-button size="mini" type="text" v-if="scope.row.isPublish === 0" @click="handleDelete(scope.row)"
            v-hasPermi="['form:definition:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <Dialog ref="dialogRef" @refresh="getList"></Dialog>
    <formDialog v-if="showFormDialog" v-model:visible="showFormDialog" :type="'2'" :formName="formName"
      :formId="formId"></formDialog>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    onMounted,
    onActivated,
    getCurrentInstance
  } from 'vue'
  import {
    useRoute
  } from 'vue-router'
  import {
    listDefinition,
    delDefinition,
    publish,
    unPublish,
    copyDef
  } from "@/api/form/definition";
  import Dialog from "./dialog.vue";
  import formDialog from "./formDialog.vue";
  import {
    useDict
  } from '@/utils/dict'
  import {
    parseTime
  } from '@/utils/ruoyi'
  import {
    ElMessageBox,
    ElMessage
  } from 'element-plus'

  // 字典数据
  const {
    dict
  } = useDict(['is_publish', 'activity_status'])

  // 路由实例
  const route = useRoute()

  // 组件实例（用于访问全局属性）
  const {
    proxy
  } = getCurrentInstance()

  // 响应式变量
  const loading = ref(true)
  const imgUrl = ref("")
  const flowChart = ref(false)
  const uniqueId = ref("")
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const definitionList = ref([])
  const formName = ref("")
  const formId = ref("")
  const showFormDialog = ref(false)
  const dialogRef = ref(null)

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    formCode: null,
    formName: null,
    version: null,
    orderByColumn: null,
    isAsc: null
  })

  // 组件挂载时执行
  onMounted(() => {
    getList()
  })

  // 组件激活时执行
  onActivated(() => {
    const time = route.query.t
    if (time != null && time !== uniqueId.value) {
      uniqueId.value = time
      queryParams.pageNum = Number(route.query.pageNum) || 1
      getList()
    }
  })

  /** 查询表单定义列表 */
  const getList = () => {
    loading.value = true
    listDefinition(queryParams)
      .then(response => {
        definitionList.value = response.rows
        total.value = Number(response.total)
      })
      .catch(error => {
        console.error('获取表单定义列表失败:', error)
        ElMessage.error('获取数据失败，请重试')
      })
      .finally(() => {
        loading.value = false
      })
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    if (proxy?.$refs.queryForm) {
      proxy.$refs.queryForm.resetFields()
    }
    handleQuery()
  }

  // 多选框选中数据处理
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    if (dialogRef.value) {
      dialogRef.value.show()
    }
  }

  /** 表单设计按钮操作 */
  const handleDesign = (row) => {
    if (row.isPublish === 1) {
      formName.value = row.formName
      formId.value = row.id
      showFormDialog.value = true
    } else {
      const params = {
        pageNum: queryParams.pageNum
      }
      // 假设$tab是全局注册的标签页工具
      if (proxy?.$tab) {
        proxy.$tab.openPage("表单设计", `/form/form-design/index/${row.id}`, params)
      } else {
        console.warn('$tab 全局属性未定义')
      }
    }
  }

  /** 发布按钮操作 */
  const handlePublish = (id) => {
    ElMessageBox.confirm(`是否确认发布表单定义编号为"${id}"的数据项？`)
      .then(() => publish(id))
      .then(() => {
        getList()
        ElMessage.success("发布成功")
      })
      .catch(() => {})
  }

  /** 取消发布按钮操作 */
  const handleUpPublish = (id) => {
    ElMessageBox.confirm(`是否确认取消发布表单定义编号为"${id}"的数据项？`)
      .then(() => unPublish(id))
      .then(() => {
        getList()
        ElMessage.success("取消成功")
      })
      .catch(() => {})
  }

  /** 修改按钮操作 */
  const handleUpdate = (id) => {
    if (dialogRef.value) {
      dialogRef.value.show(id)
    }
  }

  /** 删除按钮操作 */
  const handleDelete = (row) => {
    const idsToDelete = row.id || ids.value
    ElMessageBox.confirm(`是否确认删除表单定义编号为"${idsToDelete}"的数据项？`)
      .then(() => delDefinition(idsToDelete))
      .then(() => {
        getList()
        ElMessage.success("删除成功")
      })
      .catch(() => {})
  }

  /** 复制表单按钮操作 */
  const handleCopyDef = (id) => {
    ElMessageBox.confirm(`是否确认复制表单定义编号为"${id}"的数据项？`)
      .then(() => copyDef(id))
      .then(() => {
        getList()
        ElMessage.success("复制成功")
      })
      .catch(() => {})
  }

  /** 排序触发事件 */
  const handleSortChange = (column) => {
    queryParams.orderByColumn = column.prop
    queryParams.isAsc = column.order
    getList()
  }
</script>